<template>
  <div style="width:100%;">
  <p-spin :spinning="loading" size="large">
    <div class="process-tpl" :class="[isPC ? 'process-tpl--pc' : 'process-tpl--mobile']">
      <h1 v-if="!mods[processDefinitionKey]">没有找到该流程模板！</h1>
      <component
        v-else-if="!loading"
        ref="custom"
        :is="mods[processDefinitionKey]"
        :form-datas="formDatas"
        :processTplInfo="processTplInfo"
        :curUserInfo="curUserInfo"
        :creatProcess="creatProcess"
      >

        <div class="process-tpl__header" slot="header">流程标题：{{ formTitle }}</div>
        <ding slot="chart" :processDefinitionKey="processDefinitionKey"></ding>
        <chart v-if="action !== 'create'" slot="chart" />
        <submit-form
          :submit-type.sync="submitType"
          :default-form="form"
          slot="submit"
          v-if="action === 'create' || action === 'todo' || canWithdraw"
          @submit="submit"
        />
      </component>
    </div>
    
  </p-spin>
  </div>
</template>

<script>
import mods from './templates'
import Chart from '../processHost/platform/pc/chart.vue'
import Ding from '../processHost/platform/pc/ding.vue'
import SubmitForm from '../processHost/platform/pc/submitForm.vue'
import { timestampToDatetime, getParameterByName } from '@/utils/util'
import process from '@/api/process'
import oaConfig from '@/config/oa-config'

// 操作类型
const SUBMIT_TYPES = {
  AGREE: 'agree', // 同意 OR 创建流程
  REJECT: 'reject', // 驳回
  TRANSFER: 'transfer', // 转办
  WITHDRAW: 'withdraw' // 撤回
}

const action = getParameterByName('action') // 流程状态
const processDefinitionKey = getParameterByName('processDefinitionKey') // 模板名称
const processInstanceId = getParameterByName('processInstanceId') // 流程id
const taskId = getParameterByName('taskId') // 任务id
const route = getParameterByName('route') // 流程进行中的步骤，action==='todo'时有效
const node = getParameterByName('node') // 被驳回 OR 撤回
const isStart = action === 'create' || (action === 'todo' && node === 'draft') // 是否起草节点
const canWithdraw = action === 'show' && taskId !== 'null' && taskId !== '' // 可撤回
const showHandle = action === 'todo' || canWithdraw // 展示操作栏
const START_FORM_KEY = processDefinitionKey.toLocaleUpperCase() + '_START' // 起草节点的formKey
// /api/mes-manufacture/mfScientific/getByProcessId/{orocessId}
export default {
  components: { Chart, SubmitForm,Ding },
  provide () {
    return {
      action,
      processDefinitionKey,
      processInstanceId,
      taskId,
      route,
      node,
      isStart,
      canWithdraw,
      showHandle,
      START_FORM_KEY
    }
  },
  inject:['routeClose','reload'],
  data () {
    return {
      mods, // 模板集合
      action,
      processDefinitionKey,
      processInstanceId,
      taskId,
      route,
      node,
      isStart,
      canWithdraw,
      processTplInfo: null, // 流程模板信息
      curUserInfo: null, // 当前用户信息
      loading: true,
      formDatas: [],
      activeName: 'record',
      SUBMIT_TYPES,
      submitType: canWithdraw ? SUBMIT_TYPES.WITHDRAW : SUBMIT_TYPES.AGREE,
      form: {
        level: 1,
        remark: ''
      },
      isPC: false
    }
  },
  computed: {
    formTitle () {
      const createForm = this.formDatas.find(data => data.formKey === START_FORM_KEY)
      return createForm?.variables?.title || (this.curUserInfo?.name + '发起的' + this.processTplInfo?.processDefinitionName)
    }
  },
  mounted () {
    Promise.all([this.init(), this.getFormDatas()]).then(res => {
      this.loading = false
    })
    this.resize()
    this.getUerInfo()
    window.addEventListener('resize', this.resize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.resize)
  },
  methods: {
    resize () {
      this.isPC = window.innerWidth > 500
    },
    getUerInfo(){
      process.userInfo().then(res=>{
        this.curUserInfo = res.data
        console.log(res.data)//登录人信息
      })
    },
    close(){
      this.routeClose(this.$route)
    },
    init () {
      return process.getProcessParams(processDefinitionKey).then(res => {
        if (res.code === 0) {
          this.processTplInfo = res.data
          return process.userInfo()
        }
        return res
      }).then(res => {
        if (res.code === 0) {
          this.curUserInfo = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    getFormDatas () {
      if (this.action === 'create') return Promise.resolve()
      return process.getExampleBusiness(processInstanceId).then(res => {
        if (res.code === 0) {
          console.log(res)
          if(Object.prototype.toString.call(res.data)!=='[object Array]'){
            let arrList = []
            arrList.push(res.data)
            this.formDatas = (arrList || []).map(data => {
            try {
              data.variables = JSON.parse(data.variables)
            } catch (err) {
              data.variables = {}
            }
            if (data.formKey === START_FORM_KEY) {
              this.form.level = data.variables.level || 1
            }
            return data
          })
              
          }else{
            this.formDatas = (res.data || []).map(data => {
            try {
              data.variables = JSON.parse(data.variables)
            } catch (err) {
              data.variables = {}
            }
            if (data.formKey === START_FORM_KEY) {
              this.form.level = data.variables.level || 1
            }
            return data
          })
          }
          
        }
      })
    },
    creatProcess (variables, formKey = START_FORM_KEY) {
      const params = {
        formKey,
        remark: this.form.remark,
        processDefinitionKey: processDefinitionKey,
        variables: {
          level: this.form.level,
          title: `${this.formTitle}(${timestampToDatetime(Date.now(), 1)})`,
          ...variables
        }
      }
      return process.creatExampleProcess(params)
    },
    submitProcess (variables, formKey = this.route) {
      const params = {
        processInstanceId: processInstanceId,
        comment: this.form.remark,
        taskId: this.taskId
      }
      if (formKey) {
        params['formKey'] = formKey
        params['variables'] = variables
      }
      return process.completeTask(params)
    },
    rejectProcess () {
      const params = {
        comment: this.form.remark,
        taskId: this.taskId
      }
      return process.rejectTask(params).then(res => {
        if (res.code === 0) {
          this.$message.success('已驳回')
          return true
        } else {
          this.$message.error(res.msg)
          return false
        }
      })
    },
    transferProcess () {
      if (!this.form.assigneeId) {
        this.$message.error('请选择转办的人')
        return false
      } else {
        const params = {
          comment: this.form.remark,
          taskId: this.taskId,
          assigneeId: this.form.assigneeId
        }
        return process.transferTask(params).then(res => {
          if (res.code === 0) {
            this.$message.success('转办操作提交成功')
            return true
          } else {
            this.$message.error(res.msg)
            return false
          }
        })
      }
    },
    withdrawProcess () {
      const params = {
        comment: this.form.remark,
        taskId: taskId
      }
      return process.retractTask(params).then(res => {
        if (res.code === 0) {
          this.$message.success('撤回操作提交成功')
          return true
        } else {
          this.$message.error(res.msg)
          return false
        }
      })
    },
    beforeSubmit () {
      return new Promise(resolve => {
        if (this.$refs?.custom?.getVariables) {
          resolve(this.$refs.custom.getVariables())
        } else {
          resolve([true, {}])
        }
      }).then(([valid, variables]) => {
        if (valid) {
          if (action === 'create') {
            // 发起流程
            return this.creatProcess(variables)
          } else if (isStart) {
            // 起草节点，重新发起流程
            return this.submitProcess({
              ...variables,
              level: this.form.level // 可以重新编辑紧急度
            }, START_FORM_KEY)
          } else {
            // 审批流程
            return this.submitProcess(variables)
          }
        } else {
          return null
        }
      }).then(res => {
        if (res?.code === 0) {
          this.$message.success('提交成功')
          
          return true
        } else if (res?.msg) {
          this.$message.error(res.msg)
          return true
        } else {
          return false
        }
      })
    },
    submit (form) {
      this.form = { ...form }
      new Promise((resolve) => {
        if (this.submitType === SUBMIT_TYPES.AGREE) {
          resolve(this.beforeSubmit())
        } else if (this.submitType === SUBMIT_TYPES.REJECT) {
          if(!this.form.remark){
            this.$message.warning('请填写备注信息')
          }else{
            resolve(this.rejectProcess())
          }
        } else if (this.submitType === SUBMIT_TYPES.TRANSFER) {
          resolve(this.transferProcess())
        } else if (this.submitType === SUBMIT_TYPES.WITHDRAW) {
          resolve(this.withdrawProcess())
        }
      }).then(willClose => {
        if (willClose) {
          this.evBus.$emit('reflsh')
          this.close()
          // window.opener = null
          // window.open('', '_self')
          // window.location.href = 'about:blank'
          // window.close()
          // if (window.opener && window.opener.dispatchEvent) {
          //     window.opener.dispatchEvent(new Event('getTableData'))
          // } else {
          //     window.opener.fireEvent(new Event('getTableData'))
          // }
          // window.location.href = oaConfig.baseUrl
          // window.location.href = oaConfig.baseUrl + '/workflow/request/ViewRequestOS.jsp?reflush=1'
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.process-tpl {
  &--pc {
    width: 100%;
    margin: 0 auto;
    border: 1px solid #e8e8e8;
    padding: 20px;
  }
  &--mobile {
    width: 100%;
    height: 100vh;
  }
}
.process-tpl__header {
  font-size: 16px;
  margin-bottom: 18px;
  text-align: center;
}
.process-tpl__form {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  position: relative;
}
.process-tpl__form-title {
  font-size: 16px;
  margin-bottom: 10px;
}
.process-tpl__form-item {
  min-height: 35px;
  display: flex;
  border: 1px solid #e8e8e8;
  &:not(:last-child) {
    border-bottom: none;
  }
}
.process-tpl__form-item-label {
  flex: 1;
  border-right: 1px solid #e8e8e8;
  padding: 0 16px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.process-tpl__form-item-content {
  flex: 1;
  padding: 0 16px;
  display: flex;
  align-items: center;
  &.between {
    justify-content: space-between;
    padding: 3px 16px;
  }
}
.process-tpl__form-submit-btn {
  align-self: baseline;
  height: 52px;
}
</style>
